package com.linkage.jz.bankruptcy.activity.Project.ZQUser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ZQBaseProjectCrDecInfo;
import com.linkage.seapeak.activity.project.ExamineAdvActivity;
import com.linkage.seapeak.utils.CommonUtils;
import com.linkage.seapeak.view.QuickPopView;

/**
 * A login screen that offers login via email/password.
 */
public  class CreateZQBCApplyActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = CreateZQBCApplyActivity.class.getSimpleName();

    public static final String KEY_CREDITORID = "KEY_CREDITORID";
    public static final String KEY_PROJECTID = "KEY_PROJECTID";
    private static final String KEY_BIGTYPE = "KEY_BIGTYPE";
    public static final String KEY_TYPE = "KEY_TYPE";
    public static final String KEY_EDITING = "KEY_EDITING";

    /**
     * @param context    上下文
     * @param creditorId 债权人ID
     * @param projectId  项目Id
     * @param bigtype    // 0表示企业，1表示自然债权人，2标识税务机关
     * @param type       0:管理人; 1:债权人
     */
    public static void start(Context context, String creditorId, String projectId, String bigtype, int type, ZQBaseProjectCrDecInfo filesInfo) {
        Intent intent = new Intent(context, CreateZQBCApplyActivity.class);
        intent.putExtra(KEY_CREDITORID, creditorId);
        intent.putExtra(KEY_PROJECTID, projectId);
        intent.putExtra(KEY_BIGTYPE, bigtype);
        intent.putExtra(KEY_TYPE, type);
        intent.putExtra(KEY_EDITING, filesInfo);
        context.startActivity(intent);
    }

    EditText base_money, base_interest_money, base_other_money;
    Button top_back;
    TextView top_mune1, base_tatal_money;

    private EditText interestDescEt, remarkLeftToAdminDescEt, et_note;
    private CheckBox hasPriorityCb, hasNotPriorityCb;
    private LinearLayout hasPriorityLayout;
    private EditText priorityBaseMoneyEt, priorityInterestEt, priorityDescEt;
    private String mCreditorId;
    private ZQBaseProjectCrDecInfo mEditInfo;
    private String mBigType;
    private int mType;

    private String mProjectId;


    private TextView popClick;

    private View.OnFocusChangeListener calTotalListener = (view, b) -> {
        if (!b && view instanceof EditText) validatesInput((EditText) view);
        calcTotal();
        calcChange();
    };

    private View.OnFocusChangeListener validatesInputListener = (view, b) -> {
        if (!b && view instanceof EditText) validatesInput((EditText) view);
        calcChange();
    };

    private CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (!b) return;
            if (compoundButton == hasPriorityCb) {
                hasPriorityLayout.setVisibility(View.VISIBLE);
                hasNotPriorityCb.setChecked(false);
                hasNotPriorityCb.setEnabled(true);
                hasPriorityCb.setEnabled(false);
            } else if (compoundButton == hasNotPriorityCb) {
                hasPriorityLayout.setVisibility(View.GONE);
                hasPriorityCb.setChecked(false);
                hasPriorityCb.setEnabled(true);
                hasNotPriorityCb.setEnabled(false);
            }
        }
    };

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        top_back.setOnClickListener(this);
        top_mune1.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        ((TextView) findViewById(R.id.top_title)).setText("补充申报");
    }

    @Override
    public void initView() {
        top_back = findViewById(R.id.top_back);
        top_mune1 = findViewById(R.id.top_mune1);

        base_tatal_money = findViewById(R.id.base_tatal_money);
        base_money = findViewById(R.id.base_money);
        base_interest_money = findViewById(R.id.base_interest_money);
        base_other_money = findViewById(R.id.base_other_money);
        interestDescEt = findViewById(R.id.interest_desc);
        remarkLeftToAdminDescEt = findViewById(R.id.remark_left_to_admin_desc);
        hasPriorityCb = findViewById(R.id.ck_priority);
        hasNotPriorityCb = findViewById(R.id.ck_priority_not);
        hasPriorityLayout = findViewById(R.id.ck_has_priority_layout);

        priorityBaseMoneyEt = findViewById(R.id.priority_base_money);
        priorityInterestEt = findViewById(R.id.priority_interest_money);
        priorityDescEt = findViewById(R.id.priority_desc);
        et_note = findViewById(R.id.et_note);

        popClick = findViewById(R.id.pop_click);
        /**
         * 弹窗
         */
        popClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QuickPopView.show(CreateZQBCApplyActivity.this);
            }
        });

        // 0表示企业债权人，1表示自然债权人，2标识税务机关债权人
        switch (mBigType) {
            case "2":
                findViewById(R.id.creditor_type_layout).setVisibility(View.GONE);
                ((TextView) findViewById(R.id.tv0)).setText("正税:");
                ((TextView) findViewById(R.id.tv1)).setText("滞纳金:");
                findViewById(R.id.interest_desc_layout).setVisibility(View.GONE);
                base_other_money.setHint("请填写您需要向管理说明的相关内容");
                break;
            case "0":
            case "1":
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_zq_bc_apply);
        mBigType = getIntent().getStringExtra(KEY_BIGTYPE);
        if (mBigType == null) mBigType = "0";
        mType = getIntent().getIntExtra(KEY_TYPE, 0);

        mProjectId = getIntent().getStringExtra(KEY_PROJECTID);
        mCreditorId = getIntent().getStringExtra(KEY_CREDITORID);
        mEditInfo = getIntent().getParcelableExtra(KEY_EDITING);
        super.onCreate(savedInstanceState);
        fillWithinfo(mEditInfo);
        initListener();
    }

    private void fillWithinfo(@NonNull ZQBaseProjectCrDecInfo info) {
        if ("2".equals(mBigType)) {
            if (info.getDeclareAmountRegularTax() != null)
                base_money.setText(info.getDeclareAmountRegularTax());
            if (info.getDeclareAmountOverdueFine() != null)
                base_interest_money.setText(info.getDeclareAmountOverdueFine());
        } else {
            if (info.getDeclareAmountPrincipal() != null)
                base_money.setText(info.getDeclareAmountPrincipal());
            if (info.getDeclareAmountInterest() != null)
                base_interest_money.setText(info.getDeclareAmountInterest());
        }
        if (info.getDeclareAmountOther() != null)
            base_other_money.setText(info.getDeclareAmountOther());
        calcTotal();
        if (info.getDeclareAmountInterestDetail() != null)
            interestDescEt.setText(info.getDeclareAmountInterestDetail());
        if (info.getDeclareAmountOtherDetail() != null)
            remarkLeftToAdminDescEt.setText(info.getDeclareAmountOtherDetail());
        if (info.getPreferredCreditorRights().equals("true")) { //todo
            hasPriorityLayout.setVisibility(View.VISIBLE);
            hasNotPriorityCb.setChecked(false);
            hasNotPriorityCb.setEnabled(true);
            hasPriorityCb.setChecked(true);
            hasPriorityCb.setEnabled(false);
        } else {
            hasPriorityLayout.setVisibility(View.GONE);
            hasPriorityCb.setChecked(false);
            hasPriorityCb.setEnabled(true);
            hasNotPriorityCb.setChecked(true);
            hasNotPriorityCb.setEnabled(false);
        }
        if (info.getGuaranteePriority() != null)
            priorityBaseMoneyEt.setText(info.getGuaranteePriority());
        if (info.getOtherPriority() != null)
            priorityInterestEt.setText(info.getOtherPriority());
        if (info.getPreferredCreditorRightsDetail() != null)
            priorityDescEt.setText(info.getPreferredCreditorRightsDetail());
        if (info.getCreditorRightsNote() != null)
            et_note.setText(info.getCreditorRightsNote());
    }

    private void initListener() {
        base_money.setOnFocusChangeListener(calTotalListener);
        base_interest_money.setOnFocusChangeListener(calTotalListener);
        base_other_money.setOnFocusChangeListener(calTotalListener);
        base_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                calcTotal();
                calcChange();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        base_interest_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                calcTotal();
                calcChange();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        base_other_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                calcTotal();
                calcChange();
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });




        priorityBaseMoneyEt.setOnFocusChangeListener(validatesInputListener);
        priorityInterestEt.setOnFocusChangeListener(validatesInputListener);
        priorityBaseMoneyEt.setOnFocusChangeListener(validatesInputListener);
        interestDescEt.setOnFocusChangeListener(validatesInputListener);
        remarkLeftToAdminDescEt.setOnFocusChangeListener(validatesInputListener);
                et_note.setOnFocusChangeListener(validatesInputListener);
        hasPriorityCb.setOnCheckedChangeListener(checkedChangeListener);
        hasNotPriorityCb.setOnCheckedChangeListener(checkedChangeListener);

    }

    private void validatesInput(EditText editText) {
        Editable input = editText.getText();
        int index = input.toString().indexOf(".");
        if (index < 0) {
            if (input.length() != 0) input.append(".00");
        } else if (index < input.length() - 3) {
            input.delete(index + 3, input.length());
        } else if (index == input.length() - 1) {
            if (input.length() == 1) input.insert(0, "0");
            input.append("00");
        } else if (index == input.length() - 2) {
            input.append("0");
        }
    }

    private void calcChange() {
        String str_base_money = base_money.getText().toString();
        String str_base_interest_money = base_interest_money.getText().toString();
        String str_base_other_money = base_other_money.getText().toString();

        double double_base_money = 0.00;
        double double_base_interest_money = 0.00;
        double double_base_other_money = 0.00;


        double double_base_money_cur = 0.00;
        double double_base_interest_money_cur = 0.00;
        double double_base_other_money_cur = 0.00;

        try {
            double_base_money = Double.parseDouble(str_base_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            double_base_interest_money = Double.parseDouble(str_base_interest_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            double_base_other_money = Double.parseDouble(str_base_other_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if ("2".equals(mBigType)) {
            if (mEditInfo.getDeclareAmountRegularTax() != null) {
                try {
                    double_base_money_cur = Double.parseDouble(mEditInfo.getDeclareAmountRegularTax());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (mEditInfo.getDeclareAmountOverdueFine() != null) {
                try {
                    double_base_interest_money_cur = Double.parseDouble(mEditInfo.getDeclareAmountOverdueFine());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } else {
            if (mEditInfo.getDeclareAmountPrincipal() != null) {
                try {
                    double_base_money_cur = Double.parseDouble(mEditInfo.getDeclareAmountPrincipal());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (mEditInfo.getDeclareAmountInterest() != null) {
                try {
                    double_base_interest_money_cur = Double.parseDouble(mEditInfo.getDeclareAmountInterest());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        }

        if (mEditInfo.getDeclareAmountOther() != null) {
            try {
                double_base_other_money_cur = Double.parseDouble(mEditInfo.getDeclareAmountOther());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }


        if (double_base_money_cur != double_base_money) {
            base_money.setBackgroundResource(R.color.text_eee_color);
        }
        if (double_base_interest_money_cur != double_base_interest_money)
        {
            base_interest_money.setBackgroundResource(R.color.text_eee_color);
          }
        if (double_base_other_money_cur !=double_base_other_money)
        {
            base_other_money.setBackgroundResource(R.color.text_eee_color);
        }



        if (mEditInfo.getGuaranteePriority() != null) {
            if(!priorityBaseMoneyEt.getText().toString().equalsIgnoreCase(mEditInfo.getGuaranteePriority()))
            {
                priorityBaseMoneyEt.setBackgroundResource(R.color.text_eee_color);
            }
        }


        if (mEditInfo.getOtherPriority() != null) {
            if(!priorityInterestEt.getText().toString().equalsIgnoreCase(mEditInfo.getOtherPriority()))
            {
                priorityInterestEt.setBackgroundResource(R.color.text_eee_color);
            }

        }


        if (mEditInfo.getPreferredCreditorRightsDetail() != null) {
            if(!priorityDescEt.getText().toString().equalsIgnoreCase(mEditInfo.getPreferredCreditorRightsDetail()))
            {
                priorityDescEt.setBackgroundResource(R.color.text_eee_color);
            }

        }

        if (mEditInfo.getCreditorRightsNote() != null) {
            if(!et_note.getText().toString().equalsIgnoreCase(mEditInfo.getCreditorRightsNote()))
            {
                et_note.setBackgroundResource(R.color.text_eee_color);
            }

        }


    }


    private void calcTotal() {
        String str_base_money = base_money.getText().toString();
        String str_base_interest_money = base_interest_money.getText().toString();
        String str_base_other_money = base_other_money.getText().toString();
        double double_base_money = 0.00;
        double double_base_interest_money = 0.00;
        double double_base_other_money = 0.00;
        try {
            double_base_money = Double.parseDouble(str_base_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            double_base_interest_money = Double.parseDouble(str_base_interest_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            double_base_other_money = Double.parseDouble(str_base_other_money);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        double total = double_base_money + double_base_interest_money + double_base_other_money;
        if (total > 0) base_tatal_money.setText(CommonUtils.resetMoney_nodot(String.valueOf(total)));
        else base_tatal_money.setText("0.00");


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                onBackPressed();
                break;
            case R.id.top_mune1:
                //下一步
                if(!checkMoney())
                {
                    return;
                }
                calcTotal();

                if (checkAmountValidate()) {
                    syncEdit();
                    CreateZQBCApplyTwoActivity.start(this, mCreditorId, mProjectId, mType, mEditInfo);
                    finish();
                }
                break;
        }
    }

    public void syncEdit() {
        Editable editable;
        editable = base_money.getText();
        if (editable.length() > 0) {
            if ("2".equals(mBigType)) mEditInfo.setDeclareAmountRegularTax(editable.toString());
            else mEditInfo.setDeclareAmountPrincipal(editable.toString());
        }
        else {
            Toast.makeText(this, "请填写申报金额", Toast.LENGTH_SHORT).show();
            return;
        }
        editable = base_interest_money.getText();
        if ("2".equals(mBigType)) {
            if (editable.length() > 0) mEditInfo.setDeclareAmountOverdueFine(editable.toString());
        }
        else if (editable.length() > 0) mEditInfo.setDeclareAmountInterest(editable.toString());
        editable = base_other_money.getText();
        if (editable.length() > 0) mEditInfo.setDeclareAmountOther(editable.toString());
        editable = interestDescEt.getText();
        if (editable.length() > 0) mEditInfo.setDeclareAmountInterestDetail(editable.toString());
        editable = remarkLeftToAdminDescEt.getText();
        if (editable.length() > 0) mEditInfo.setDeclareAmountOtherDetail(editable.toString());
        mEditInfo.setPreferredCreditorRights(hasPriorityCb.isChecked() ? "true" : "false");
        mEditInfo.setDeclareAmountTotal(base_tatal_money.getText().toString());

        editable = priorityBaseMoneyEt.getText();
        if (editable.length() > 0) mEditInfo.setGuaranteePriority(editable.toString());
        editable = priorityInterestEt.getText();
        if (editable.length() > 0) mEditInfo.setOtherPriority(editable.toString());
        editable = priorityDescEt.getText();
        if (editable.length() > 0) mEditInfo.setPreferredCreditorRightsDetail(editable.toString());

        editable = et_note.getText();
        if (editable.length() > 0) mEditInfo.setCreditorRightsNote(editable.toString());


    }

    private boolean checkMoney() {
        String str_base_money = base_money.getText().toString();
        String str_base_interest_money = base_interest_money.getText().toString();
        String str_base_other_money = base_other_money.getText().toString();
        String str_priorityBaseMoneyEt  = priorityBaseMoneyEt.getText().toString();
        String str_priorityInterestEt  = priorityInterestEt.getText().toString();
        if(!CommonUtils.vailMoney(CreateZQBCApplyActivity.this,str_base_money)) {
            return  false;
        }
        if(!CommonUtils.vailMoney(CreateZQBCApplyActivity.this,str_base_interest_money)) {
            return  false;
        }
        if(!CommonUtils.vailMoney(CreateZQBCApplyActivity.this,str_base_other_money)) {
            return  false;
        }

        if(!CommonUtils.vailMoney(CreateZQBCApplyActivity.this,str_priorityInterestEt)) {
            return  false;
        }

        if(!CommonUtils.vailMoney(CreateZQBCApplyActivity.this,str_priorityBaseMoneyEt)) {
            return  false;
        }

        return true;
    }

    private boolean checkAmountValidate() {
        boolean validate = !base_tatal_money.getText().equals("0.00");
        if (!validate) Toast.makeText(this, "请填写申报金额", Toast.LENGTH_SHORT).show();
        return validate;
    }

}

